<?php

namespace App\Domain\Role\Services;

use App\Domain\Role\Dao\RoleDao;
use App\Domain\Role\Models\RoleModel;
use App\Exceptions\BadRequestException;
use Illuminate\Support\Facades\DB;


class RoleService
{
    /**
     * 修改角色及其权限
     * @param $params
     * @return array
     * @throws \Exception
     */
    public function update($params)
    {
        $roleDao = new RoleDao();
//        if (!$params['permission_ids']) {
//            throw new BadRequestException("权限不等都为空");
//        }
        DB::beginTransaction();
        try {
            if ($params['role_id'] == '-1') {
                $role = $roleDao->create([
                    'show_name' => $params['show_name'],
                    'name' => $params['show_name'],
                    'describe' => $params['describe'],
                ]);
                $role = $roleDao::findByName($params['show_name']);
//                dd(explode(',', $params['permission_ids']));
                $role->syncPermissions(explode(',', $params['permission_ids']));
            } else {
                $role = $roleDao->findById($params['role_id']);
                if (empty($role)) {
                    throw new BadRequestException('角色不存在');
                }
                $role = $roleDao->update($role, [
                    'show_name' => $params['show_name'],
                    'name' => $params['show_name'],
                    'describe' => $params['describe'],

                ]);
                $role = $roleDao::findByName($params['show_name']);
//                dd($role);
                $role->syncPermissions(explode(',', $params['permission_ids']));
//                $permissionIdArr = explode(',', trim($params['permission_ids']));
//                $permissionIdArr = array_merge_not_null(explode(',', trim($params['permission_ids'])), explode(',', trim($params['pad_permission_ids'], ',')));
//                $permissionIdArr = array_merge(array_flip(array_flip($permissionIdArr)));
//                $role->syncPermissions($permissionIdArr);
            }
            DB::commit();
        } catch (\Throwable $e) {
            DB::rollBack();
            throw new \Exception($e->getMessage(), $e->getCode(), $e);
        }
        return [];
    }


    public function list()
    {
        $roleDao = new RoleDao();
        $list = $roleDao->findAll();
        return $list;
    }

    /**
     * 删除角色
     * @param $params
     * @return array
     */
    public function delete($roleId)
    {
        $roleDao = new RoleDao();
        $roleDao->delete($roleId);
        return [];
    }
}
